package job

import (
	task "Monitor/task"
	"errors"

	"github.com/gogf/gf/os/gcron"
)

type CronConfig struct {
	Worktime string
	JobF     func()
	Name     string
	Tb       *task.TaskBase
	Params   bool
	Entry    *gcron.Entry
}

func NewCron(s string, callback func(), name string) (c *CronConfig) {
	c = &CronConfig{
		Worktime: s,
		JobF:     callback,
		Name:     name,
		Tb:       task.NewTask(),
		Params:   true,
	}
	return
}

func (c *CronConfig) SetNoParams() {
	c.Params = false
}

func (c *CronConfig) AddCron() (err error) {
	if c.Params == false {
		c.Entry, err = gcron.AddSingleton(c.Worktime, c.JobF, c.Name)
		if err != nil {
			return
		}
		return
	} else {
		c.Entry, err = gcron.AddSingleton(c.Worktime, c.Tb.DefaultTask, c.Name)
		if err != nil {
			return
		}
		return
	}
}

//设置应答任务
func (c *CronConfig) SetReplyTask() {
	if c.Tb.Request.Reply == nil {
		c.Tb.Request.Reply = NewTaskReply(c.Name)
	}
}

type reqTask func(req *task.TaskRequest, resp *task.TaskResponse)

func (c *CronConfig) SetCallTask(callback reqTask) {
	if c.Params == true {
		c.Tb.TaskCallback = callback
		if c.Tb.Request.RequestCallParams == nil {
			c.Tb.Request.Reply.TaskErr(errors.New("参数为空"))
		}
	}
}

func (c *CronConfig) SetTaskParams(s string) {
	c.Tb.Request.RequestCallParams = task.NewTaskRequestParams(s)
}
